/*
    The MIT License

    Copyright (c) 2009 IFMO/GameDev Studio

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
*/

#pragma once


#include "core.h"

/*-----------------------------------------------------------------------------
	Lua interface :
-----------------------------------------------------------------------------*/

ELuaInterface::ELuaInterface( lua_State *L, const char *file, uint line )
 : stack_guard(L, file, line)
{
	this->L	=	L;
}


ELuaInterface::~ELuaInterface( void )
{

}

void ELuaInterface::SetStackGrow( int num )
{
	stack_guard.SetStackGrow(num);
}

/*-----------------------------------------------------------------------------
	Error stuff :
-----------------------------------------------------------------------------*/

//
//	ELuaInterface::Error
//
void ELuaInterface::Error( const char *fmt, ... )
{
	va_list argp;
	va_start(argp, fmt);
	luaL_where(L, 1);
	lua_pushvfstring(L, fmt, argp);
	va_end(argp);
	lua_concat(L, 2);
	
	lua_error(L);
}


//
//	ELuaInterface::Warning
//
void ELuaInterface::Warning( const char *fmt, ... )
{
	va_list argp;
	va_start(argp, fmt);
	luaL_where(L, 1);
	lua_pushvfstring(L, fmt, argp);
	va_end(argp);
	lua_concat(L, 2);
	
	LOG_WARNING("%s", lua_tostring(L, -1));
	
	lua_pop(L, 1);
}


//
//	ELuaInterface::ArgumentError
//
void ELuaInterface::ArgumentError( int idx, const char *type, const char *what )
{
	luaL_argerror(L, idx, va(": expected "LUA_QS" - "LUA_QS, what, type));
}


/*-----------------------------------------------------------------------------
	LuaInterface::GetField :
-----------------------------------------------------------------------------*/

#define LUA_GET_FIELD(isfunc, tofunc)					\
	if ( lua_istable(L, idx)==0 ) return false;			\
	lua_getfield(L, idx, key);							\
	if (isfunc(L, -1))	{ value = tofunc(L, -1); lua_pop(L, 1); return true; } else		\
						{ lua_pop(L, 1); return false; }								\


bool ELuaInterface::GetField( int idx, const char *key, bool &value )		{	LUA_GET_FIELD( lua_isboolean,	lua_toboolean	);	}
bool ELuaInterface::GetField( int idx, const char *key, int &value )		{	LUA_GET_FIELD( lua_isnumber,	lua_tonumber	);	}
bool ELuaInterface::GetField( int idx, const char *key, uint &value )		{	LUA_GET_FIELD( lua_isnumber,	lua_tonumber	);	}
bool ELuaInterface::GetField( int idx, const char *key, float &value )		{	LUA_GET_FIELD( lua_isnumber,	lua_tonumber	);	}
bool ELuaInterface::GetField( int idx, const char *key, EString &value )	{	LUA_GET_FIELD( lua_isstring,	lua_tostring	);	}


bool ELuaInterface::GetSubTable( int idx, const char *key )
{
	if (!lua_istable(L, idx)) return false;
	
	lua_getfield(L, idx, key);
	
	if (!lua_istable(L, -1)) {
		lua_pop(L, 1);
		return false;
	}

	return true;
}


/*-----------------------------------------------------------------------------
	LuaInterface::Require???Field()
-----------------------------------------------------------------------------*/

bool			LuaIsNumber	 (lua_State *L, int idx) {	return lua_isnumber( L, idx );	}
bool			LuaIsBoolean (lua_State *L, int idx) {	return lua_isboolean( L, idx );	}
bool			LuaIsString	 (lua_State *L, int idx) {	return lua_isstring( L, idx );	}

double			LuaToNumber	 (lua_State *L, int idx) {	return lua_tonumber( L, idx );	}
bool			LuaToBoolean (lua_State *L, int idx) {	return lua_toboolean( L, idx );	}
const char	*	LuaToString	 (lua_State *L, int idx) {	return lua_tostring( L, idx );	}


template<typename Type, typename IsFunc, typename ToFunc>
Type LuaReqField( lua_State *L, int idx, const char *key, const char *type_name, Type defvalue, IsFunc isfunc, ToFunc tofunc )
{
	int tt = lua_type(L, idx);
	if (tt!=LUA_TTABLE) {
		luaL_error(L, "object at %d is not a table, got '%s'", idx, lua_typename(L, tt));
	}

	lua_getfield(L, idx, key);															\
	
	if (isfunc(L, -1)) {
		Type value = tofunc(L, -1);
		lua_pop(L, 1);
		return value;
	} else {
		luaL_error(L, "field '%s' is not '%s' or nil", key, type_name);
		return defvalue;
	}
}
						

double	ELuaInterface::RequireFieldNumber	( int idx, const char *key ) { 	return LuaReqField<double>	(L, idx, key, "number",		0,		LuaIsNumber,	LuaToNumber);	}
bool	ELuaInterface::RequireFieldBoolean	( int idx, const char *key ) { 	return LuaReqField<bool>	(L, idx, key, "boolean",	false,	LuaIsBoolean,	LuaToBoolean);	}
EString ELuaInterface::RequireFieldString	( int idx, const char *key ) {	return LuaReqField<EString>	(L, idx, key, "string",		"",		LuaIsString,	LuaToString);	}


void ELuaInterface::RequireFieldTable( int idx, const char *key )
{
	if (!lua_istable(L, idx)) { 
		Error("object at %d is not a table", idx); 
	}
	
	lua_getfield(L, idx, key);
}

/*-----------------------------------------------------------------------------
	LuaInterface::RequireXXX
-----------------------------------------------------------------------------*/

//
//	ELuaInterface::RequireNumber
//
double ELuaInterface::RequireNumber( int arg, const char *what )
{
	if (!lua_isnumber(L, arg)) {
		ArgumentError(arg, "number", what);
		return 0;
	} else {
		return lua_tonumber(L, arg);
	}
}


//
//	ELuaInterface::RequireBoolean
//
bool ELuaInterface::RequireBoolean( int arg, const char *what )
{
	if (!lua_isboolean(L, arg)) {
		LuaArgumentError(L, arg, "boolean", what);
		return false;
	} else {
		return lua_toboolean(L, arg)!=0;
	}
}


//
//	ELuaInterface::RequireString
//
EString ELuaInterface::RequireString( int arg, const char *what )
{
	if (!lua_isstring(L, arg)) {
		LuaArgumentError(L, arg, "string", what);
		return false;
	} else {
		return EString( lua_tostring(L, arg) );
	}
}



/*-----------------------------------------------------------------------------
	Referenced functions :	
-----------------------------------------------------------------------------*/

int ELuaInterface::RefFunction( int idx, const char *what )
{
	LUA_STACK_GUARD(L);
	
	if (!lua_isfunction(L, idx)) {
		LuaArgumentError(L, 1, "function", "frame func");
		return LUA_NOREF;
	}
	
	lua_pushvalue(L, 1);
	
	return	luaL_ref(L, LUA_REGISTRYINDEX);
}


int ELuaInterface::CallRefFuncion( int ref, int arg_num )
{
	LUA_STACK_GUARD(L);
	return 0;
}
